package yunjiao.javatutorials.apache.kafka;

import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * 消息生成，带定时任务
 *
 * @author yangyunjiao
 */
@Slf4j
@Component
public class KafkaDemoProducer {
    private final static AtomicInteger index = new AtomicInteger(0);

    private final KafkaTemplate<String, String> kafkaTemplate;
    private static final String TOPIC = "demo-topic"; // 目标主题（需提前在 Kafka 创建）

    // 注入 Spring 自动配置的 KafkaTemplate
    public KafkaDemoProducer(KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    // 发送消息方法
    public void sendMessage(String message) {
        CompletableFuture<SendResult<String, String>> future =
                kafkaTemplate.send(TOPIC, message);

        future.whenComplete((result, ex) -> {
            if (ex == null) {
                log.info(">>> Message sent successfully: offset={}",
                        result.getRecordMetadata().offset());
            } else {
                log.error("Failed to send message", ex);
                // 这里可以添加重试逻辑或告警
            }
        });
    }

    @Scheduled(fixedDelay = 6000L)
    void logSomeStuff() {
        this.sendMessage("Message: " + index.incrementAndGet());
    }
}
